var pageObj={type:"1203",width:[600],height:[0,36,35],htmlObj:["topContainer"],paging:true,size:15};
var layoutContainer = create_layout(pageObj);
layoutContainer.layout.items[0].showHeader();
layoutContainer.layout.items[0].setText("<span style='font-weight:bold;color:#206988;'>角色管理</span>");
layoutContainer.layout.items[1].showHeader();
layoutContainer.layout.items[1].setText("<span style='font-weight:bold;color:#206988;'>导航菜单</span>");
var roleGrid;
var dhxWins,editRoleWin;
var editRoleInfo;
var editPermissions=[];

$(function(){
	$('.dhtmlxLayoutPolySplitterVer div').css("width","3px");//分割线
    $('#pagingArea').css({"height":"30px","bottom":"5px","left":"1px"});//分页

    layoutContainer.layout.items[0].hideHeader();
	dhxWins=new dhtmlXWindows();
	dhxWins.setImagePath(basePP + "js/dhtmlx/dhtmlxWindows/codebase/imgs/");
	initGrid();
	loadData();
	initTree();
	layoutContainer.layout.attachEvent("onPanelResizeFinish",function(){
		if(layoutContainer.layout.items[0].getWidth()<650){
			$func.alert("当前宽度已到达最小限制","red");
			layoutContainer.layout.items[0].setWidth(650);
		}
    });
});

//初始化按钮Form
function doOnButtFormInit(){
	if (typeof (buttForm) == 'object') {
		buttForm.attachEvent("onButtonClick",function(name,command) {
			switch (command) {
			case 'add':editRole('add');break;
			case 'edit':editRole('edit');break;
			case 'freeze':freezeOrUnfreeze();break;
			case 'refresh':loadData();break;
			case 'save':saveRole();break;
			case 'delete':deleteRole();break;
			}
		});
	}
}
function initGrid() {
	roleGrid = layoutContainer.grid[0];
	dmjplugs.grid.createGrid({
		sm:'ch',
		  skin:'dhx_skyblue',
		  srcc:true,
		  validate : true,
		  columns:[{header:'id',id:'id',width:90},
		           {header:'角色名',id:'role_name',width:120},
		           {header:'备注',id:'remark',width:100},
		           {header:'状态',id:'status',type:'combo',width:100},
		           {header:'排序',id:'sort_num',width:80},
		           {header:'创建时间',id:'gmt_create',width:'*'}]
	},roleGrid);
	roleGrid.setTotal(0);
    roleGrid.setColumnHidden(0,true);
	roleGrid.enableEditEvents(false,false,false);
    roleGrid.getColumnCombo(roleGrid.getColIndexById('status')).addOption(statusComboData);
	roleGrid.attachEvent("onRowSelect", getDetailPermission);
	roleGrid.attachEvent("onRowDblClicked", function () {
		editRole('edit');
	});
	roleGrid.attachEvent("loadPagingData", function(first, limit){
		loadData(first, limit);
	});
}

function loadData(first,limit) {
	$("#freeze").html("<span>作废</span>");
	if (!limit) {
		first = 0;
		limit = roleGrid.getPageRowLimit();
		roleGrid.clearAll();
		roleGrid.setTotal(0);
	}
	var postData="pageNo="+parseInt(first/limit+1)+"&pageSize="+limit+"&pageCount="+roleGrid.getPageTotal();
	$.ajax({
        url: basePath+'manageRole/findPageData',
        type: 'post',
        dataType: 'json',
        data:encodeURI(postData),
        success: function (data) {
        	if(!data||!data.result){
        		$func.alert(data.message?data.message:'获取角色失败','red');
        		return;
        	}
            if(data.rowCount>0){
            	roleGrid.parse(data.gridr, "json");
            	roleGrid.setTotal(data.rowCount);
                roleGrid.uncheckAll();
            }else{
            	$func.alert('未查询到角色','red');
            }
        }
    });
}

function initTree(){
	tree = layoutContainer.tree[0];
	tree.setSkin('dhx_skyblue');
	tree.setImagePath(basePP + "js/dhtmlx/dhtmlxTree/codebase/imgs/");
	tree.enableTreeLines(true);
	tree.enableCheckBoxes(1);
	tree.enableThreeStateCheckboxes(true);
	tree.enableTreeImages(0);
	tree.attachEvent("onClick", function(id) {
		tree.openItem(id);
	});
	loadMenuTree();
}

function loadMenuTree(){
	$.ajax({
        url: basePath+'leftMenu',
        type: 'get',
        dataType: 'json',
        success: function (data) {
            if (!data || !data.result) {
                $func.alert(data.message?data.message:'获取菜单失败', "red");
                return;
            }
            tree.loadXMLString(data.content);
            var parentlist = tree.getAllItemsWithKids();
            if(parentlist&&parentlist.length>0){
                var p_nodes = parentlist.split(",");
                for ( var i = 0; i < p_nodes.length; i++){
                    tree.openAllItems(p_nodes[i]);
                }
            }
        },
        error:function(xhr, textStatus, statusText){
            $func.alert('获取菜单请求失败:'+textStatus+":"+statusText, "green");
        }
    });
}

function editRole(type) {
	if(type!='add'&&type!='edit')
		return;
	if(type=='edit'){
		var roles = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
		if (roles == null||roles.length > 1) {
			$func.alert("请选择一个角色再操作！","red");
			return;
		}
		editRoleInfo=roles[0];
	}
	editRoleWin = dhxWins.createWindow("editRoleWin", 20, 30, 320, 250);
	editRoleWin.center();
	editRoleWin.setModal(true);
	editRoleWin.bringToTop();
	editRoleWin.setText("<span style=\"font-size:14px;\">"+(type=="add"?"新增角色":"编辑角色")+"</span>");
	editRoleWin.denyResize();
	editRoleWin.button("minmax1").hide();
	editRoleWin.button("park").hide();
	editRoleWin.attachURL(basePath+"manageRole/editRole?type="+type); 

}

function freezeOrUnfreeze() {
	var roles = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
	if (roles == null||roles.length > 1) {
		$func.alert("请选择一个角色再操作！","red");
		return;
	}
	var confirmArr = "是否作废角色【"+roles[0].role_name +"】？ <br/><font color='#ff66;'>作废后，已分配角色账号将失去相应功能权限！</font>";
	var status=roles[0].status;
	if( status!='enabled' )  confirmArr = "是否恢复角色【"+roles[0].role_name +"】？ <br/><font color='#ff66;'></font>";
	var postData={id:roles[0].id,status:status!='enabled'?"enabled":"disabled"};
    var id= $.trim(roles[0].id);
    if(!id){
        $func.alert("所选数据有问题,请刷新页面!",	"id");
        return;
    }
    //验证
    checkParam(id);

	$func.confirm({
   		content : confirmArr,
   		ok : function() {
   			$.ajax({
   		        url: basePath+'manageRole/changeState' ,
   		        type: 'post',
   		        dataType: 'json',
   		        data:postData,
   		        success: function (back) {
   		        	if(!back||!back.result){
   		        		$func.alert(back.message?back.message:"操作失败","red");
   		        		return;
   		        	}
   	            	$func.alert("操作成功！", "green");
   	            	loadData();
   		        }
   		    });
   		}
   	});
}

function saveRole() {
	var roles = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
	if (roles == null||roles.length > 1) {
		$func.alert("请选择一个角色再保存！","red");
		return;
	}

    var id= $.trim(roles[0].id);
    if(!id){
        $func.alert("所选数据有问题,请刷新页面!",	"id");
        return;
    }
    //验证
    checkParam(id);

	var permissionidslist = getAllSelectedPermissionId();
	if(permissionidslist.length==0){
		$func.alert("请分配导航菜单后再保存！","red");
		return;
	}
	if(editPermissions.length==permissionidslist.length){
		var existsCount=0;
		$.each(permissionidslist,function(k,v){
			if($.inArray(v,editPermissions)!=-1)
				existsCount++;
		});
		if(existsCount==editPermissions.length){
			$func.alert("保存设置成功","green");
			return;
		}
	}

	var postData=""+permissionidslist;
	var postData={menus:permissionidslist};
	//alert(postData);
	//console.log(postData);
 	$.ajax({
        url: basePath+'manageRole/saveMenus/'+id,
        type: 'post',
       // contentType:'application/json;charset=utf-8',
        dataType: 'json',
        data:postData,
        success: function (data) {
        	if(!data||!data.result){
        		$func.alert(data.message?data.message:'获取菜单失败');
        		return;
        	}
        	$func.alert("保存设置成功","green");
        	editPermissions=permissionidslist;
        }
    });
}

//获取选中的权限信息，以逗号缀加
function getAllSelectedPermissionId() {
	var idList = [];
	var list = $.trim(tree.getAllCheckedBranches());
	if(list!=""&&list.length>0){
		var as = list.split(",");
		for ( var j = 0; j < as.length; j++) 
			idList.push(as[j])
	}
	return idList;
}

//根据角色获得权限列表tree
function getDetailPermission(rowId, celId) {
	editStatus = roleGrid.cells(rowId, roleGrid.getColIndexById('status')).getValue();
	// console.log($("#freeze").length);
	$("#freeze").html("<span>"+(editStatus=='enabled'?"作废":editStatus=='freeze'?"恢复":"恢复")+"</span>");
	editPermissions=[];
	var roles = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
	if (roles == null||roles.length > 1) {
		$func.alert("只能勾选一个角色！","red");
		return;
	}
	if(!roles[0] ) return;

    var id= $.trim(roles[0].id);
    if(!id){
        $func.alert("所选数据有问题,请刷新页面!",	"id");
        return;
    }
    //验证
    checkParam(id);
	var allTree = tree.getAllCheckedBranches();
	var as = allTree.split(",");
	for(var j = 0; j < as.length; j++) 
		tree.setCheck(as[j], 0);
	var parentlist = tree.getAllChildless();
	var p_nodes = parentlist.split(",");
	//console.log(JSON.stringify(p_nodes));
	$.ajax({
        url: basePath+'manageRole/showMenus/'+id,
        type: 'get',
        dataType: 'json',
        success: function (data) {
        	if(!data||!data.result||!data.content){
        		//$func.alert(data.message?data.message:'获取菜单列表失败');
        		return;
        	}        	
        	$.each(data.content,function(k,v){
        		for ( var i = 0; i < p_nodes.length; i++){
        			if (v == p_nodes[i])
        				tree.setCheck(v, 1);
        		}
        		editPermissions.push(v);
        	});
        }
    });
};

function deleteRole() {
	var roles = getCheckedRowsByGrid(roleGrid, roleGrid.getColIndexById('select'));
	if (roles == null||roles.length > 1) {
		$func.alert("请选择一个角色再操作！","red");
		return;
	}
	if(roles[0].status == 'enabled'){
		$func.alert("不能删除有效的角色！","red");
		return;
	}
	var postData={id:roles[0].id};
	var confirmArr = "是否删除角色【"+roles[0].role_name +"】？ <br/><font color='#ff66;'></font>";
	//验证
	// checkParam(id);
	$func.confirm({
		content : confirmArr,
		ok : function() {
			$.ajax({
				url: basePath+'manageRole/deleteRole' ,
				type: 'post',
				dataType: 'json',
				data:postData,
				success: function (back) {
					if(!back||!back.result){
						$func.alert(back.message?back.message:"删除失败","red");
						return;
					}
					$func.alert("删除成功！", "green");
					loadData();
				}
			});
		}
	});
}